package com.erp.order.listener;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.erp.order.mapper.ErpSellerChildOrderMapper;
import com.erp.order.mapper.ErpSellerOrderLogMapper;
import com.erp.order.mapper.ErpSellerOrderMapper;
import com.erp.order.mapper.ErpSellerOrderProductMapper;
import com.erp.order.service.IErpSellerOrderLogService;
import com.erp.order.service.PullOrderFromAeService;
import com.rabbitmq.client.Channel;
import com.ruoyi.ae.api.domain.AeStoreChildOrder;
import com.ruoyi.ae.api.domain.AeStoreOrder;
import com.ruoyi.ae.api.domain.AeStoreOrderProduct;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.OrderLogType;
import com.ruoyi.common.core.enums.OrderProcessFlag;
import com.ruoyi.gather.api.RemoteCollectAbsentSkuService;
import com.ruoyi.gather.api.RemoteCollectProductService;
import com.ruoyi.gather.api.RemoteCollectProductSkuService;
import com.ruoyi.gather.api.domain.ErpCollectAbsentSku;
import com.ruoyi.gather.api.domain.ErpCollectProductSku;
import com.ruoyi.order.api.domain.ErpSellerChildOrder;
import com.ruoyi.order.api.domain.ErpSellerOrder;
import com.ruoyi.order.api.domain.ErpSellerOrderLog;
import com.ruoyi.order.api.domain.ErpSellerOrderProduct;
import com.ruoyi.system.api.RemoteSysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 拉取AE新订单监听
 * @Author: j.zh
 * @Date: 2024/5/2
 * @Version: 4.0.0
 **/
@Slf4j
@Component
@RabbitListener(queues = "pull.new.order.queue", ackMode = "MANUAL")
public class PullNewOrderFromAeListener {

    @Resource
    PullOrderFromAeService pullOrderFromAeService;
    @Resource
    ErpSellerOrderMapper erpSellerOrderMapper;
    @Resource
    IErpSellerOrderLogService erpSellerOrderLogService;
    @Resource
    ErpSellerChildOrderMapper erpSellerChildOrderMapper;
    @Resource
    RemoteCollectProductService remoteCollectProductService;
    @Resource
    RemoteCollectProductSkuService remoteCollectProductSkuService;
    @Resource
    RemoteCollectAbsentSkuService remoteCollectAbsentSkuService;
    @Resource
    ErpSellerOrderProductMapper erpSellerOrderProductMapper;


    private static Map<String, Object> orderStatusTacticsMap = OrderProcessFlag.getOrderStatusCollocationMap();
    String statusStr = "WAIT_BUYER_ACCEPT_GOODS,PLACE_ORDER_SUCCESS,WAIT_SELLER_SEND_GOODS,FINISH,RISK_CONTROL";
    String inProcessOrderStatus = "103,1031,105,106,1061,1071,1072,1073,1074,108,109,115";

    /**
     * 拉取AE新订单
     *
     * @param info
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    public void listener(String info, Channel channel, Message message) throws IOException {

        try {
            log.debug("=============接收消息，消息队列开始执行（拉取AE新订单）");
            // 回复队列消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            // 将JSON字符串转换为Map
            JSONObject divideJson = JSONObject.parseObject(info);
            Map<String, Object> divideMap = (Map<String, Object>) divideJson;
            divide(divideMap);
        } catch (Exception e) {
            // TODO 消费异常，设置入库操作

            System.out.println("=============执行异常：" + e.toString());
        }

    }


    /**
     * @param divideMap
     * @Description: 新订单入库
     * @Author: j.zh
     * @Date: 2024/5/2
     * @Version: 4.0.0
     **/
    @Transactional
    public R<Object> divide(Map<String, Object> divideMap) {
        Integer type = (Integer) divideMap.get("type");

        // 获取新订单信息
        ErpSellerOrder newOrder = pullOrderFromAeService.encapsulationErpOrder(divideMap);

        // 保存订单至ERP
        //循环该订单
        Map<String, Object> map = new HashMap<>();
        //判断数据库中是否已存在该订单号
        // 状态为0 标志为新订单 则进入新订单方法
        map = disposeNewOrders(newOrder);
        newOrder = (ErpSellerOrder) map.get("order");
        newOrder.setCreateTime(new Date());
        newOrder.setUpdateTime(new Date());

        //处理订单数据
        insertNewOrder(newOrder);
        OrderLogType orderLogType = (OrderLogType) map.get("orderLogType");
        String remark = (String) map.get("remark");
        String orderProcessFlag = (String) map.get("orderProcessFlag");
        String erpInnerOrderStatus = (String) map.get("erpInnerOrderStatus");
        if (orderLogType != null) {
            //当日志类型不为空时，再生成日志
            //处理map，生成日志
            erpSellerOrderLogService.createOrderLog(newOrder.getOrderId(), null, orderLogType, remark, orderProcessFlag, erpInnerOrderStatus);
        }
        return R.ok();
    }


    /**
     * @param order
     * @return
     * @Description: 处理新订单
     * @Author: j.zh
     * @Date: 2024/5/11
     * @Version: 4.0.0
     **/
    public Map<String, Object> disposeNewOrders(ErpSellerOrder order) {
        Map<String, Object> map = new HashMap<>();
        //判断订单类型
        String orderProcessFlag = null;
        OrderLogType orderLogType = null;
        String erpInnerOrderStatus = null;
        String remark = "（订单已被获取到）";
        switch (order.getOrderStatus()) {
            case "PLACE_ORDER_SUCCESS":
                //买家待支付
                erpInnerOrderStatus = "100";
                orderProcessFlag = OrderProcessFlag.Begin.getInfo();
                orderLogType = OrderLogType.CreateOrder;
                break;
            case "RISK_CONTROL":
                //封控24小时
                erpInnerOrderStatus = "102";
                orderProcessFlag = OrderProcessFlag.Begin.getInfo();
                orderLogType = OrderLogType.RiskControlOrder;
                break;
            case "WAIT_SELLER_SEND_GOODS":
                // 买家已付款等待卖家发货
                erpInnerOrderStatus = "101";
                orderProcessFlag = OrderProcessFlag.Begin.getInfo();
                orderLogType = OrderLogType.WaitSellerSendGoods;
//                findOrderReceiptInfo(order.getOrderId());

                List<ErpSellerChildOrder> childOrders = erpSellerChildOrderMapper.selectList(
                        new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getOrderId, order.getOrderId())
                );
                // 判断该商品是用户自采还是公司采集，如果是用户采集，则更新采集状态为采集可见
                if (childOrders.size() > 0) {
                    List<String> skuCodeList = childOrders.stream()
                            .map(ErpSellerChildOrder::getSkuCode)    // 抽出每个ErpSellerStoreProductGroup对象的id
                            .collect(Collectors.toList());   // 创建新的集合
                    for (String skuCode : skuCodeList) {
                        remoteCollectProductService.setProToOrder(skuCode);
                    }
                }
                break;
            case "WAIT_BUYER_ACCEPT_GOODS":
                //待收货
                erpInnerOrderStatus = "107";
                orderProcessFlag = OrderProcessFlag.Out.getInfo();
                orderLogType = OrderLogType.OutOrderSendGoodsOK;
                break;
            case "FINISH":
                //已结束
                erpInnerOrderStatus = "114";
                orderProcessFlag = OrderProcessFlag.Out.getInfo();
                orderLogType = OrderLogType.OutOrderFinish;
                break;
            case "SELLER_PART_SEND_GOODS":
                //部分支付
                erpInnerOrderStatus = "701";
                orderProcessFlag = OrderProcessFlag.Out.getInfo();
                orderLogType = OrderLogType.OutOrderSendGoodsOK;
                break;
            default:
                erpInnerOrderStatus = "701";
                orderProcessFlag = OrderProcessFlag.Out.getInfo();
                remark = pullOrderFromAeService.problemRemark(order.getOrderStatus());
                orderLogType = OrderLogType.OutOrderTurnProblem;
                break;
        }
        order.setErpInnerOrderStatus(erpInnerOrderStatus);
        order.setOrderProcessFlag(orderProcessFlag);
        map.put("order", order);
        map.put("orderProcessFlag", orderProcessFlag);
        map.put("orderLogType", orderLogType);
        map.put("remark", remark);
        map.put("erpInnerOrderStatus", erpInnerOrderStatus);
        return map;

    }

    /**
     * @param order
     * @return
     * @Description: 新订单入库ERP
     * @Author: j.zh
     * @Date: 2024/5/11
     * @Version: 4.0.0
     **/
    private void insertNewOrder(ErpSellerOrder order) {
        if (order.getSellerChildOrderList() != null && order.getSellerChildOrderList().size() > 0) {
            List<ErpCollectProductSku> erpCollectProductSku = new ArrayList<>();
            ErpCollectAbsentSku erpCollectAbsentSku = new ErpCollectAbsentSku();
            ErpCollectProductSku collectProductSku = null;
            //向优先采集表中插入信息
            for (ErpSellerChildOrder erpSellerChildOrder : order.getSellerChildOrderList()) {
                //判断该订单的商品的skucode在数据库中是否存在
                collectProductSku = new ErpCollectProductSku();
                collectProductSku.setSkuCode(erpSellerChildOrder.getSkuCode());
                collectProductSku.setDelFlag("0");
                erpCollectProductSku = remoteCollectProductSkuService.getCollectProductSkuList(collectProductSku);
                if (erpCollectProductSku.size() > 0) {
                    //查询该商品是否已属于该表
                    erpCollectAbsentSku = remoteCollectAbsentSkuService.getBySkuCode(erpSellerChildOrder.getSkuCode());
                    if (erpCollectAbsentSku == null) {
                        erpCollectAbsentSku = new ErpCollectAbsentSku();
                        String url = "https://www.aliexpress.us/item/";
                        //向晓翔表里插入数据
                        erpCollectAbsentSku.setOrderId(erpSellerChildOrder.getOrderId().toString());
                        erpCollectAbsentSku.setChildOrderId(erpSellerChildOrder.getChildOrderId());
                        erpCollectAbsentSku.setSkuCode(erpSellerChildOrder.getSkuCode());
                        erpCollectAbsentSku.setCollectLink(url + erpSellerChildOrder.getProductId() + ".html");
                        erpCollectAbsentSku.setStatus("0");
                        remoteCollectAbsentSkuService.addSku(erpCollectAbsentSku);
                    }
                }
//                erpSellerChildOrderMapper.insertOrUpdate(BeanUtil.copyProperties(erpSellerChildOrder, ErpSellerChildOrder.class));
            }
            erpSellerChildOrderMapper.insertBatch(order.getSellerChildOrderList());
        }

        if (order.getSellerOrderProductList().size() > 0) {
            for (ErpSellerOrderProduct orderProduct : order.getSellerOrderProductList()) {
                ErpSellerOrderProduct orderProductSel = new ErpSellerOrderProduct();
                if (ObjectUtils.isNotNull(orderProduct.getSkuCode())) {
                    orderProductSel = erpSellerOrderProductMapper.selectOne(
                            new LambdaQueryWrapper<ErpSellerOrderProduct>()
                                    .eq(ErpSellerOrderProduct::getSkuCode, orderProduct.getSkuCode())
                                    .eq(ErpSellerOrderProduct::getChildId, orderProduct.getChildId())
                                    .eq(ErpSellerOrderProduct::getOrderId, orderProduct.getOrderId())
                    );
                } else {
                    orderProductSel = erpSellerOrderProductMapper.selectOne(
                            new LambdaQueryWrapper<ErpSellerOrderProduct>()
                                    .eq(ErpSellerOrderProduct::getChildId, orderProduct.getChildId())
                                    .eq(ErpSellerOrderProduct::getOrderId, orderProduct.getOrderId())
                                    .last("limit 1")
                    );
                }

                if (orderProductSel != null) {
                    orderProduct.setId(orderProductSel.getId());
                }
                orderProduct.setCreateTime(new Date());
                orderProduct.setUpdateTime(new Date());
                erpSellerOrderProductMapper.insert(orderProduct);
            }
        }

        // 将新订单入库ERP
        erpSellerOrderMapper.insert(order);
    }


}
